'use strict'

const { validate } = use('Validator')
const log = use('Logger')
const moment = require('moment') //日期格式化插件
moment.locale('zh-cn') //设为北京时区
const Util = require('../../../Lib/Util')
//引用Service里的类并初始化
const priceGeneratorService = new (require(`../../../Services/PriceGeneratorService`))()

class PriceGeneratorController {
  //---------------------------------------------
  //async 方法名(ctx)，固定格式，其中ctx是一个对象，表示请求的上下文，ctx = { request, response, session }
  //每个Controller的方法return时，都需通过return Util.end2front()，使得返回的对象的格式具有一致性
  //---------------------------------------------

  /**
   * 注册新用户，开始试算
   * 传参
   * random_id
   *
   * @returns object
   */
  async initfun(ctx) {
    try {
      let requestAll = ctx.request.all()
      let random_id = requestAll.random_id

      if (!Util.isNumber(random_id)) {
        return Util.error2front({
          isShowMsg: true,
          msg: 'random_id is not a number',
          code: 5000,
          track: '9834jld6',
        })
      }

      let body = {
        random_id: random_id,
      }

      ctx.body = body

      //调用service层来处理业务逻辑
      const result = await priceGeneratorService.initfun(ctx)

      //返回结果给前端
      return Util.end2front({
        msg: result.msg,
        data: result.data,
      })
    } catch (err) {
      return Util.error2front({
        //isShowMsg: true,
        msg: err.message,
        code: 9000,
        track: 'initfun2',
      })
    }
  }

  async update(ctx) {
    try {
      let requestAll = ctx.request.all()
      let random_id = requestAll.random_id
      let is_last = requestAll.is_last
      let data = requestAll.data
      let sess_key = 'price_generator_' + random_id

      let sess = JSON.parse(ctx.session.get(sess_key))

      for (let item of data) {
        sess.push(item)
      }

      let sess_str = JSON.stringify(sess)
      ctx.session.put(sess_key, sess_str)

      let fb = {}

      if (is_last) {
        //计算费用
        ctx.body = { random_id: random_id }

        //调用service层来处理业务逻辑
        fb = await priceGeneratorService.update(ctx)
      }

      return Util.end2front({
        msg: 'OK',
        data: fb.data,
      })
    } catch (err) {
      return Util.error2front({
        //isShowMsg: true,
        msg: err.message,
        code: 9000,
        track: 'update',
      })
    }
  }
}

module.exports = PriceGeneratorController
